package cn.com.gas.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.stereotype.Controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import cn.com.common.constants.Constants;
import cn.com.common.result.DataResult;
import cn.com.gas.entity.GasJyzxxImportCygxxEntity;
import cn.com.gas.entity.GasStationinfoEntity;
import cn.com.gas.service.GasJyzxxImportCygxxService;
import cn.com.gas.service.GasStationinfoService;
import cn.com.gas.vo.excel.GasJyzxxImportCygxxExcel;
import cn.com.system.service.impl.HttpSessionService;
import cn.com.util.TsBqUtils;

/**
 * 加油罐
 *
 * @author shaochangyang
 * @email l2l84o7o5@live.com
 * @date 2024-07-20 15:23:52
 */
@Controller
@RequestMapping("/gas/cygxx")
@Slf4j
public class GasJyzxxImportCygxxController {
	@Autowired
	private GasJyzxxImportCygxxService gasJyzxxImportCygxxService;
	@Autowired
	private GasStationinfoService gasStationinfoService;
	@Autowired
	private HttpSessionService httpSessionService;
	
	@Value("${file.path}")
	private String filePath;
	@Value("${file.url}")
	private String fileUrl;
	
	
	@ApiOperation(value = "新增")
	@PostMapping("/add")
	// @RequiresPermissions("gasJyzxxImportCygxx:add")
	@ResponseBody
	public DataResult add(@RequestBody GasJyzxxImportCygxxEntity gasJyzxxImportCygxx) {
		gasJyzxxImportCygxxService.saveCygxx(gasJyzxxImportCygxx);
		return DataResult.success();
	}

	@ApiOperation(value = "删除")
	@DeleteMapping("/delete")
	// @RequiresPermissions("gasJyzxxImportCygxx:delete")
	@ResponseBody
	public DataResult delete(@RequestBody @ApiParam(value = "id集合") List<String> ids) {
		gasJyzxxImportCygxxService.removeByIdsCygxx(ids);
		return DataResult.success();
	}

	@ApiOperation(value = "更新")
	@PutMapping("/update")
	// @RequiresPermissions("gasJyzxxImportCygxx:update")
	@ResponseBody
	public DataResult update(@RequestBody GasJyzxxImportCygxxEntity gasJyzxxImportCygxx) {
		gasJyzxxImportCygxxService.updateByIdCygxx(gasJyzxxImportCygxx);
		return DataResult.success();
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@ApiOperation(value = "查询分页数据")
	@PostMapping("/list")
	// @RequiresPermissions("gasJyzxxImportCygxx:list")
	@ResponseBody
	public DataResult findListByPage(@RequestBody GasJyzxxImportCygxxEntity gasJyzxxImportCygxx) {
		Page page = new Page(gasJyzxxImportCygxx.getPage(), gasJyzxxImportCygxx.getLimit());
		LambdaQueryWrapper<GasJyzxxImportCygxxEntity> queryWrapper = Wrappers.lambdaQuery();
		// 查询条件示例
		if (TsBqUtils.isNotNull(gasJyzxxImportCygxx.getJcxxId())) {
			queryWrapper.eq(GasJyzxxImportCygxxEntity::getJcxxId, gasJyzxxImportCygxx.getJcxxId());

		} else {
			return DataResult.fail("加油站ID为NULL");
		}

		IPage<GasJyzxxImportCygxxEntity> iPage = gasJyzxxImportCygxxService.page(page, queryWrapper);
		return DataResult.success(iPage);
	}

	@ApiOperation(value = "导出模板")
	@PostMapping("/exportTemplate")
	// @RequiresPermissions("gasJyzxxImportCygxx:list")
	@ResponseBody
	public DataResult exportTemplate(@RequestBody GasStationinfoEntity vo) {

    	
		String currentDeptId = httpSessionService.getCurrentDeptId();

		LambdaQueryWrapper<GasStationinfoEntity> queryWrapper = Wrappers.lambdaQuery();
		if (Constants.TAX_COUNTES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))) {
			// 县区局
			queryWrapper.eq(GasStationinfoEntity::getType, "group");
			queryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");
			queryWrapper.eq(GasStationinfoEntity::getTaxorgcode, currentDeptId);
		} else if(Constants.TAX_CITIES.equals(TsBqUtils.getTaxOrgLevel(currentDeptId))){
			// 市局 
			queryWrapper.eq(GasStationinfoEntity::getType, "group");
			queryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");
			queryWrapper.like(GasStationinfoEntity::getTaxorgcode, currentDeptId.substring(0, 5));
		}else{
			// 省局
		}

		if (TsBqUtils.isNotNull(vo.getName())) {
			queryWrapper.like(GasStationinfoEntity::getName, vo.getName());
		}

		List<GasStationinfoEntity> list = gasStationinfoService.list(queryWrapper);

		if (list.size() > 0) {
			List<GasJyzxxImportCygxxExcel> excelList = new ArrayList<>();
			for (GasStationinfoEntity entity : list) {

				GasJyzxxImportCygxxExcel cygxx = GasJyzxxImportCygxxExcel.builder()
						.name(entity.getName())
						.jcxxId(entity.getId())
						.cygMc("")
						.yp("")
						.cygrj("")
						.sykcyl("")
						.yg("")
						.sg("")
						.wd("")
						.build();
				excelList.add(cygxx);
			}

			String fileName = TsBqUtils.getUUID() + ".xlsx";

			String excelPath = filePath + fileName;
			OutputStream out = null;

			try {
				out = new FileOutputStream(excelPath);
				ExcelWriter writer = EasyExcelFactory.getWriter(out);

				Sheet sheet1 = new Sheet(1, 0, GasJyzxxImportCygxxExcel.class);
				sheet1.setSheetName("数据");
				writer.write(excelList, sheet1);
				// 将上下文中的最终 outputStream 写入到指定文件中
				writer.finish();
				File excelFile = new File(excelPath);
				List<Object> excelFileInfo = new ArrayList<>();
				excelFileInfo.add(fileName);
				excelFileInfo.add(excelFile.length());
				excelFileInfo.add(fileUrl + "/" + fileName);

				return DataResult.success(excelFileInfo);

			} catch (FileNotFoundException e) {
				e.printStackTrace();
				return DataResult.fail("xlsx生成失败：" + e.toString());
			} finally {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
					return DataResult.fail("xlsx生成失败：" + e.toString());
				}
			}
		} else {
			return DataResult.fail("传入的ids为null！");
		}
	}
	
	@ApiOperation(value = "导入数据")
	@PostMapping("/importData")
	// @RequiresPermissions("gasJyzxxImportCygxx:list")
	@ResponseBody
	public DataResult importData(@RequestParam("file") MultipartFile[] files) {

		if (files != null && files.length > 0) {
			for (MultipartFile file : files) {
				InputStream inputStream = null;
				try {
					inputStream = file.getInputStream();
					Sheet sheet = new Sheet(1, 1);
					List<Object> readList = EasyExcelFactory.read(inputStream, sheet);
					List<GasJyzxxImportCygxxEntity> cygxxList = new ArrayList<>();

					for (Object object : readList) {
						List<String> list = TsBqUtils.castList(object, String.class);
						
						String name = list.get(0);//@ExcelProperty(value = "加油站名称", index = 1)
						String jcxxId = list.get(1);//@ExcelProperty(value = "加油站id", index = 2)
						String cygMc = list.get(2);//@ExcelProperty(value = "储油罐名称", index = 3)
						String yp = list.get(3);//@ExcelProperty(value = "油品", index = 4)
						String cygrj = list.get(4);//@ExcelProperty(value = "储油罐容积", index = 5)
						String sykcyl = list.get(5);//@ExcelProperty(value = "剩余库存油量", index = 6)
						String yg = list.get(6);//@ExcelProperty(value = "油高", index = 7)
						String sg = list.get(7);//@ExcelProperty(value = "水高", index = 8)
						String wd = list.get(8);//@ExcelProperty(value = "温度", index = 9)
						log.info("正在处理加油站：" + name + ",ID:" + jcxxId);
						if (TsBqUtils.isNull(jcxxId)) {
							return DataResult.fail("表格中存在【加油站id】为空的！");
						}
						GasJyzxxImportCygxxEntity cygxx = new GasJyzxxImportCygxxEntity();
						
						cygxx.setJcxxId(jcxxId);
						cygxx.setCygMc(cygMc);
						cygxx.setYp(yp);
						cygxx.setCygrj(cygrj);
						cygxx.setSykcyl(sykcyl);
						cygxx.setYg(yg);
						cygxx.setSg(sg);
						cygxx.setWd(wd);
						
						cygxxList.add(cygxx);
					}
					
					for (GasJyzxxImportCygxxEntity entity : cygxxList) {
						gasJyzxxImportCygxxService.saveCygxx(entity);
					}

				} catch (Exception e) {
					log.error("importData" + e.getMessage());
					
				} finally {
					if (inputStream != null) {
						try {
							inputStream.close();
						} catch (IOException e) {
							e.printStackTrace();
							return DataResult.fail(e.getMessage());
						}
					}
				}
			}
		}

		return DataResult.success();
	}
	
	
	
}
